/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reyes.mysite.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import reyes.mysite.jdo.Blog;
import reyes.mysite.jdo.Comment;
import reyes.mysite.dao.GenericDAO;

/**
 *
 * @author reyesyang
 */
public class PostCommentAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        PostCommentActionForm commentForm = (PostCommentActionForm) form;

        String blogKey = commentForm.getBlogKey();
        String role = commentForm.getRole();
        String poster = commentForm.getPoster();
        String email = commentForm.getEmail();
        String website = commentForm.getWebsite();
        String content = commentForm.getContent();
        GenericDAO<Object> dao = new GenericDAO<Object>();
        Blog blog = (Blog) dao.getById(Blog.class, Long.valueOf(blogKey));

        dao.beginTransaction();
        try {
            Comment comment = new Comment(role, poster, email, website, content, blog);
            blog.getComments().add(comment);
            blog.setCommentCount(blog.getCommentCount() + 1);
            dao.save(blog);
            dao.commitTransaction();
        } catch (Exception e) {
            System.out.println("Can't post comment for reason: " + e.getMessage());
        } finally {
            if (dao.isActiveTransaction()) {
                dao.rollbackTransaction();
            }
            request.setAttribute("blog", blog);
            dao.closePM();
        }

        String destPath;
        UserService userService = UserServiceFactory.getUserService();
        if (userService.isUserLoggedIn()) {
            if (userService.isUserAdmin()) {
                destPath = "adminBlogDetails";
            } else {
                destPath = "blogDetails";
            }
        } else {
            destPath = "blogDetails";
        }

        return mapping.findForward(destPath);
    }
}
